﻿using System.Text.RegularExpressions;

namespace Babelfish.Converters
{
    /// <summary>
    /// 
    /// </summary>
    public class XmlConverter
    {
        /// <summary>
        /// Converts to XML document.
        /// </summary>
        /// <param name="node">The node.</param>
        /// <returns></returns>
        public static System.Xml.XmlDocument ConvertToXmlDocument(INode node)
        {
            var doc = new System.Xml.XmlDocument();
            
            AppendNodeToXmlDocument(node, doc, null);

            

            return doc;
        }

        /// <summary>
        /// Appends the node to XML document.
        /// </summary>
        /// <param name="node">The node.</param>
        /// <param name="document">The document.</param>
        /// <param name="appendNode">The append node.</param>
        private static void AppendNodeToXmlDocument(INode node, System.Xml.XmlDocument document, System.Xml.XmlNode appendNode)
        {
            System.Xml.XmlElement element;

            var name = Regex.Replace(node.Name, "[^a-zA-Z]+", string.Empty);

            if(string.IsNullOrEmpty(name))
                element = document.CreateElement("value","babelfish");
            else
                element = document.CreateElement(name);

            if(node.HasValue)
                element.InnerText = node.Text;

            if (appendNode == null)
                document.AppendChild(element);
            else
                appendNode.AppendChild(element);


            foreach(var attribute in node.Attributes)
            {
                var a = document.CreateAttribute(attribute.Name);
                a.Value = attribute.Value;
                element.Attributes.Append(a);
            }

            foreach (var child in node.ChildNodes)
                AppendNodeToXmlDocument(child, document, element);
        }
    }
}
